package com.example.demo.nio;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

import static com.example.demo.nio.ByteBufferUtil.debugAll;

public class TestFileReadsAndWrites {


    public static void main(String[] args) throws FileNotFoundException {
//        read();
//        write();
        stickyHalfPack();
    }

    private static void stickyHalfPack() {

        ByteBuffer source = ByteBuffer.allocate(32);
        // 粘包半包
        source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(source);
        source.put("w are you?\nhaha!\n".getBytes());
        split(source);
    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n'){
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact();
    }

    private static void write() {
        try (FileChannel channel = new RandomAccessFile("src/main/resources/hello.txt", "rw").getChannel()) {
            ByteBuffer bf1 = StandardCharsets.UTF_8.encode("hello");
            ByteBuffer bf2 =  StandardCharsets.UTF_8.encode(" world!");
            channel.write(new ByteBuffer[]{bf1,bf2});
        }catch (IOException e) {

        }



    }

    private static void read() {
        try {
            FileChannel channel = new RandomAccessFile("src/main/resources/word.txt","r").getChannel();
            Resource resource = new ClassPathResource("word.txt");
            URI uri = resource.getURI();
            String path = uri.getPath();
            URL url = resource.getURL();
            String path1 = url.getPath();

            ByteBuffer bf1 = ByteBuffer.allocate(3);
            ByteBuffer bf2 = ByteBuffer.allocate(3);
            ByteBuffer bf3 = ByteBuffer.allocate(5);
            channel.read(new ByteBuffer[]{bf1,bf2,bf3});
            bf1.flip();
            bf2.flip();
            bf3.flip();

            debugAll(bf1);
            debugAll(bf2);
            debugAll(bf3);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
